<template>
	<view class="flex j-s a-s" :style='{width:containerW+"rpx",height:containerH+"rpx"}'>
		<image :style='{width:imgW+"rpx",height:imgH+"rpx"}' v-for="(item,i) in imgs" :src='item' :key='i'
			@click="preview(i)" />
		<view :style="{width:imgW+'rpx'}" v-if="[2,5,8].includes(imgs.length)"></view>
	</view>
</template>

<script>
	export default {
		props: {
			imgs: {
				type: Array,
				required: true
			},
			width: {
				type: [String, Number],
				default: 606
			}
		},
		data() {
			return {
				containerW: this.width,
				containerH: 200,
				imgW: 200,
				imgH: 200,
				singleImgW: 400
			}
		},
		created() {
			this.calcWH()
		},
		methods: {
			preview(i) {
				uni.previewImage({
					urls: this.imgs,
					current: i,
				})
			},
			calcWH() {
				let {
					width: w,
					imgs: {
						length: len
					}
				} = this

				if (len === 1) {
					//如果只有一张，需要特殊处理，比如长图，或者手机拍照，效果不一样
					let [src] = this.imgs
					uni.getImageInfo({
						src,
						success: ({
							width,
							height
						}) => {
							let per = width / 2 / this.singleImgW

							if (height > 2000) {
								this.imgW = this.singleImgW / 1.5
								this.imgH = this.singleImgW / 1.2
							} else {
								this.imgW = this.singleImgW
								this.imgH = height / 2 / per
							}
							this.containerH = this.imgH
						},
					})
				} else if (len === 4) {
					//多张图的话，算出平均宽度，按正方形处理，留出间隙
					this.imgW = this.imgH = Math.floor((w - 6) / 2)
					//算容器高度，留出间隙
					this.containerH = Math.ceil(this.imgs.length / 2) * (this.imgH + 3)
				} else {
					//多张图的话，算出平均宽度，按正方形处理，留出间隙
					this.imgW = this.imgH = Math.floor((w - 6) / 3)
					//算容器高度，留出间隙
					this.containerH = Math.ceil(this.imgs.length / 3) * (this.imgH + 3)
				}
			}
		}
	}
</script>

<style>
	.flex {
		display: flex;
		flex-wrap: wrap;
	}

	.j-s {
		justify-content: space-between;
	}

	.a-s {
		align-content: space-between;
	}
</style>
